package com.yogee.topseller.activity.login.view.impl;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.AppManager;
import com.yogee.core.utils.LogUtils;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.base.HttpActivity;
import com.yogee.topseller.activity.login.model.bean.CheckBean;
import com.yogee.topseller.activity.login.model.bean.SMSbean;
import com.yogee.topseller.activity.login.presenter.ResetPswPresenter;
import com.yogee.topseller.activity.login.view.IResetPswView;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.Constants;
import com.yogee.topseller.view.BasicDialog;
import com.yogee.topseller.view.ClearEditText;

import butterknife.BindView;
import butterknife.OnClick;


public class ForgetPswActivity extends HttpActivity implements IResetPswView {

    @BindView(R.id.phone)
    ClearEditText phone;
    @BindView(R.id.validate_code)
    ClearEditText validateCode;
    @BindView(R.id.get_code)
    TextView getCode;

    @BindView(R.id.confirm)
    TextView confirm;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.login_title)
    TextView login_title;

    // 倒计时
    private CountDownTimer timer;
    private ResetPswPresenter resetPresenter;
    //生成一个随机数
    private int mRadomNumber = 0;
    String flag = "";
    private String openid="",name="", headerUrl="",deviceId="",unionid="";

    /**
     * this activity layout res
     * 设置layout布局
     *
     * @return res layout xml id
     */
    @Override
    protected int getLayoutId() {
        return R.layout.activity_forget_psw;
    }

    /**
     * 页面初始化工作
     */
    @Override
    protected void initView() {

        flag = getIntent().getStringExtra("flag");
        if(flag.equals(Constants.FLAG_REGIST)){
            tv_title.setText("注册");
        }else if(flag.equals(Constants.FLAG_FORGETPASSWORD)){
            tv_title.setText("忘记密码");
        }else{
            tv_title.setText("关联手机号码");
            login_title.setVisibility(View.GONE);
            openid = getIntent().getStringExtra("openid");
            name = getIntent().getStringExtra("name");
            headerUrl = getIntent().getStringExtra("headerUrl");
            deviceId = getIntent().getStringExtra("deviceId");
            unionid = getIntent().getStringExtra("unionid");
        }
        resetPresenter = new ResetPswPresenter(this);
        mRadomNumber = AppUtil.getRandomNumber(4);
    }

    private void jumpToNext(){

        if(flag.equals(Constants.FLAG_REGIST)){
            tv_title.setText("注册");
            MobclickAgent.onEvent(ForgetPswActivity.this, "reg_yzm");
        }else if(flag.equals(Constants.FLAG_FORGETPASSWORD)){
            tv_title.setText("忘记密码");
            MobclickAgent.onEvent(ForgetPswActivity.this, "forget_yzm");
        }else{
            MobclickAgent.onEvent(ForgetPswActivity.this, "wx_reg_yzm");
        }
        startActivity(new Intent(ForgetPswActivity.this, ForgetPswSendCodeActivity.class)
                .putExtra("phoneNum", phone.getText().toString())
                .putExtra("flag",flag)
                .putExtra("openid",openid)
                .putExtra("unionid",unionid)
                .putExtra("name",name)
                .putExtra("headerUrl",headerUrl)
                .putExtra("deviceId",deviceId));
    }

    @OnClick({R.id.confirm, R.id.get_code, R.id.back,R.id.img_wx,R.id.login_title})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirm:
               if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                // 忘记密码
                if(flag.equals(Constants.FLAG_FORGETPASSWORD)){
                    MobclickAgent.onEvent(ForgetPswActivity.this, "forget_phone_next");
                    // 注册
                }else if(flag.equals(Constants.FLAG_REGIST)){
                    MobclickAgent.onEvent(ForgetPswActivity.this, "reg_phone_next");
                }else{
                    MobclickAgent.onEvent(ForgetPswActivity.this, "wx_reg_phone_next");

                }
                if (TextUtils.isEmpty(phone.getText().toString())) {
                    ToastUtils.showToast(this, "手机号码不能为空");
                } else if (!AppUtil.validatePhone(phone.getText().toString())) {
                    ToastUtils.showToast(this, "请输入正确的手机号码");
                }else{

                    if(flag.equals(Constants.FLAG_REGIST)||flag.equals(Constants.FLAG_AUTH)){
                        HttpManager.getInstance().userCheck(phone.getText().toString()).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<CheckBean>() {
                            @Override
                            public void onNext(CheckBean o) {
                                jumpToNext();
                            }
                        }, this));
                    }else{
                        jumpToNext();
                    }

                }
//                else if (TextUtils.isEmpty(validateCode.getText().toString())){
//                    ToastUtils.showToast(this, "请输入验证码");
//                }
//                else if (mRadomNumber == Integer.valueOf(validateCode.getText().toString())) {
//                    startActivity(new Intent(ForgetPswActivity.this, ResetPsActivity.class).putExtra("phoneNum", phone.getText().toString()));
//
//                } else {
//                    ToastUtils.showToast(this, "请输入正确的验证码");
//                }
                break;
            case R.id.get_code:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
                if ("重新发送".equals(getCode.getText().toString())) {
                    mRadomNumber = AppUtil.getRandomNumber(4);
                }
                if (validate()) {
                    getCode.setTextColor(getResources().getColor(R.color.gray));
                    getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1gray));
                    getCode.setClickable(false);
                    resetPresenter.sendSMS(ForgetPswActivity.this, phone.getText().toString(), mRadomNumber);
                }
                break;
            case R.id.back:
//                onBackPressed();
                try{
                    AppManager.finishActivity(LoginActivity.class);
                }catch(Exception e){

                }
                finish();
                break;
            case R.id.img_wx:
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                ToastUtils.showLongToast(this,"微信操作");
                break;
            case R.id.login_title:
                MobclickAgent.onEvent(ForgetPswActivity.this, "loginBtn","登录");
                startActivity(new Intent(ForgetPswActivity.this, LoginActivity.class));
                break;
            default:
                break;
        }
    }


    public Boolean validate() {
        if (TextUtils.isEmpty(phone.getText())) {
            ToastUtils.showToast(this, "请输入手机号");
            return false;
        } else if (!AppUtil.validatePhone(phone.getText().toString())) {
            ToastUtils.showToast(this, "请输入正确的手机号");
            return false;
        }
        return true;
    }

    public void countDownTimer() {

        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                getCode.setText("重新发送" + "(" + millisUntilFinished / 1000 + "s)");
                getCode.setTextColor(getResources().getColor(R.color.gray));
                getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1gray));
                getCode.setClickable(false);
            }

            @Override 
            public void onFinish() {
                getCode.setText("重新发送");
                getCode.setTextColor(getResources().getColor(R.color.theme_color));
                getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1_theme));
                getCode.setClickable(true);
            }
        };
        timer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null)
            timer.cancel();
    }

    @Override
    public void showMsg(String msg) {

        if(flag.equals(Constants.FLAG_AUTH)){

            if(Constants.PHONE_REGED.equals(msg)){
                BasicDialog.Builder builder = new BasicDialog.Builder(ForgetPswActivity.this);
                builder.setMessage("该手机号已注册，现在去登录？")
                        .setPositiveButton("是", new AlertDialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                            MobclickAgent.onEvent(ForgetPswActivity.this, "notLogin_tk_loginBtn");
                                Intent intent = new Intent(ForgetPswActivity.this, LoginActivity.class);
                                startActivity(intent);
                                dialog.dismiss();
                            }

                        })
                        .setNegativeButton("否", new AlertDialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                phone.setText("");
                                dialog.dismiss();
                            }
                        });

                builder.create().show();
            }else{
                ToastUtils.showToast(ForgetPswActivity.this, msg);
            }
        }else{
            ToastUtils.showToast(ForgetPswActivity.this, msg);
        }

        getCode.setTextColor(getResources().getColor(R.color.theme_color));
        getCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.corners5_stroke1_theme));
        getCode.setClickable(true);
    }

    @Override
    public void updatePassword() {

    }

    @Override
    public void updateSuccess() {
        this.finish();
    }


    @Override
    public void updateCheckCode(SMSbean smSbean) {
        if (Integer.parseInt(smSbean.getError_code()) == 0) {
            countDownTimer();
            ToastUtils.showToast(this, "验证码已经发送");
        } else {
            getCode.setClickable(true);
            ToastUtils.showToast(this, smSbean.getError_code() + ":" + smSbean.getReason());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this); //统计时长
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
